import './index.scss'
import { JSEncrypt } from 'jsencrypt'
import { DataSegment } from './datastructure/DataSegment'
import * as TOOL from './UI/tool'
import $ = require("jquery");
import { DataProcessor } from './datastructure/DataProcessor';

let CharaterTableDiv: Element = document.querySelector("#createyourfirstcharater")!;
let RerollButton: HTMLButtonElement = document.querySelector("#Reroll") as HTMLButtonElement;
let createButton: HTMLButtonElement = document.querySelector("#create") as HTMLButtonElement;
let ansSet: number[] = [0, 0, 0, 0, 0, 0];

let fields: string[] = [
    "password",
    "name",
    "age",
    "gender",
    "ethnicity",
    "occupation",
    "religion",
    "language",
    "body",
    "background",
    "STR",
    "DEX",
    "CON",
    "INT",
    "WIS",
    "CHA",
    "HP",
    "speciality",
    "skill",
    "bag"
]

RerollButton.onclick = roll4d6;

createButton.onclick = create;

function create() {
    let userData = new DataSegment();
    let ansSet2 = ansSet;
    let ok: boolean = true;
    let userName: string = "";
    let password: string = "";

    for (let key in fields) {
        let fieldHTMLValue: HTMLInputElement = document.querySelector("#" + fields[key]) as HTMLInputElement;
        if (fieldHTMLValue.value == "") {
            alert("字段不能为空");
            ok = false;
            break;
        }
        if (fields[key] == "name") {
            userName = fieldHTMLValue.value;
        }
        if (fields[key] == "password") {
            password = fieldHTMLValue.value;
            continue;
        }
        if (["STR", "DEX", "CON", "INT", "WIS", "CHA"].indexOf(key) != -1) {
            console.log(ansSet2);
            console.log(parseInt(fieldHTMLValue.value) + " " + fieldHTMLValue.value + " " + $.inArray(parseInt(fieldHTMLValue.value), ansSet2))
            let fieldHTMLValueInt: number = parseInt(fieldHTMLValue.value);
            if ($.inArray(fieldHTMLValueInt, ansSet2) >= 0) {
                ansSet2.splice($.inArray(fieldHTMLValueInt, ansSet2), 1);

            } else {
                alert("属性值请按照给出值分配");
                ok = false;
                break;
            }
        }
        let value = fieldHTMLValue.value ? fieldHTMLValue.value : "空";
        userData.put(fields[key], value);
    }
    if (ok) {
        doCreateUserData(userName, password, userData);
    }
}

function roll4d6() {

    let rollans: HTMLElement = document.querySelector("#rollans") as HTMLElement;
    ansSet = [0, 0, 0, 0, 0, 0];

    for (let i in ansSet) {
        let numSet: number[] = [0, 0, 0, 0]
        for (let j in [1, 2, 3, 4]) {
            numSet[j] = Math.floor(Math.random() * 6) + 1;
        }
        numSet.sort();
        for (let j in [2, 3, 4]) {
            ansSet[i] += numSet[j];
        }
    }
    rollans.innerHTML = ansSet.toString();
}
window.onload = roll4d6;

async function doCreateDM(userName: string, password: string, roomName: string) {
    let crypt = new JSEncrypt({ default_key_size: 2048 });
    let encrypt = new JSEncrypt({ default_key_size: 2048 });
    encrypt.setPublicKey(TOOL.setverPublicKey);

    createButton.innerText = "生成密钥中.";
    let isdone = false;
    setTimeout(function load() {
        createButton.innerText += ".";
        if (!isdone) {
            setTimeout(load, 500);
        }
    }, 500);
    crypt.getKey(async () => {
        let privateKey = crypt.getPrivateKey();
        let publicKey = crypt.getPublicKey();

        password = await TOOL.sha256(password);
        let encryptedPassword = encrypt.encrypt(password);

        $.post("love/createDM.do", {
            userName: userName,
            password: encryptedPassword,
            publicKey: publicKey,
            roomName: roomName,
        }, (data) => {
            isdone = true;
            switch (data) {
                case "USERNAME_ALREADY_IN_USE":
                    alert("用户名已被使用");
                    break;
                case "ROOMNAME_ALREADY_IN_USE":
                    alert("房间暗号已被使用");
                    return;
                case "RAS_CHIPHER_ERROR":
                    alert("证书错误");
                    return;
                case "SUCCESS":
                    window.localStorage.setItem("publicKey", publicKey);
                    window.localStorage.setItem("privateKey", privateKey);
                    window.localStorage.setItem("name", userName);
                    window.location.href = "index.html";
                    return;
                default:
                    alert("未知错误");
                    return;
            }
        });
    });

}
async function doCreateUserData(userName: string, password: string, userData: DataSegment) {
    let crypt = new JSEncrypt({ default_key_size: 2048 });
    let encrypt = new JSEncrypt({ default_key_size: 2048 });
    encrypt.setPublicKey(TOOL.setverPublicKey);
    createButton.innerText = "生成密钥中.";
    let isdone = false;
    setTimeout(function load() {
        createButton.innerText += ".";
        if (!isdone) {
            setTimeout(load, 500);
        }
    }, 500);
    crypt.getKey(async () => {
        let privateKey = crypt.getPrivateKey();
        let publicKey = crypt.getPublicKey();

        password = await TOOL.sha256(password);
        let encryptedPassword = encrypt.encrypt(password);

        $.post("love/createUserData.do", {
            userName: userName,
            password: encryptedPassword,
            publicKey: publicKey,
            userData: DataProcessor.buildString(userData)
        }, (data) => {
            isdone = true;
            switch (data) {
                case "USERNAME_ALREADY_IN_USE":
                    alert("用户名已被使用");
                    return;
                case "RAS_CHIPHER_ERROR":
                    alert("证书错误");
                    return;
                case "SUCCESS":
                    window.localStorage.setItem("publicKey", publicKey);
                    window.localStorage.setItem("privateKey", privateKey);
                    window.localStorage.setItem("name", userName);
                    window.location.href = "index.html";
                    return;
                default:
                    alert("未知错误");
                    return;
            }
        });
    });

}

let checkbox = document.getElementById("isDM") as HTMLInputElement;
checkbox!.onclick = () => {
    if (checkbox.checked) {
        (document.getElementById("roomName")! as HTMLInputElement).disabled = false;
        document.getElementById("userData")!.style.display = "none";
        createButton.onclick = () => {
            let userName = (document.getElementById("name") as HTMLInputElement).value;
            let password = (document.getElementById("password") as HTMLInputElement).value;
            let roomName = (document.getElementById("roomName") as HTMLInputElement).value;
            doCreateDM(userName, password, roomName);
        };
    } else {
        (document.getElementById("roomName")! as HTMLInputElement).disabled = true;
        document.getElementById("userData")!.style.display = "";
        createButton.onclick = create;
    }
}